"""
    Copyright 2011 Kacper Żuk <kazuldur@gmail.com>

    This file is part of pyLastPlayer.

    pyLastPlayer is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    pyLastPlayer is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with pyLastPlayer.  If not, see <http://www.gnu.org/licenses/>.
"""

from urllib.request import urlopen
from urllib.error import HTTPError
from tempfile import NamedTemporaryFile
import logging
from PyQt4 import QtCore, QtGui
from PyQt4.phonon import Phonon
from Downloader import Downloader
import LastLib

class ExtendedMediaSource(Phonon.MediaSource):
    def __init__(self, t):
        Phonon.MediaSource.__init__(self, t.file)
        self.t = t
        self.ready = False
        
class Player(QtCore.QObject):
    def __init__(self):
        QtCore.QObject.__init__(self)
        self.p = Phonon.createPlayer(Phonon.MusicCategory)
        self.p.setPrefinishMark(10000)
        self.p.setTickInterval(500)
        self.p.currentSourceChanged.connect(self.currentSourceChanged)
        self.p.prefinishMarkReached.connect(self.prefinishMarkReached)
        self.p.metaDataChanged.connect(self.metaDataChanged)
        self.p.tick.connect(self.tick)
        self.p.stateChanged.connect(self.stateChanged)
        self.p.totalTimeChanged.connect(self.totalTimeChanged)
        self.playing = False
        self.current = False
        self.log = logging.getLogger("Phonon")
        self.log.info("Initialized")
        self.d = Downloader()
        self.connect(self.d, QtCore.SIGNAL("updateStatus(QString)"), self.done)
        self.connect(self.d, QtCore.SIGNAL("started(QString)"), self.started)
        self.queue = []

    def done(self, s):
        self.emit(QtCore.SIGNAL("updateStatus(QString)"), s)

    def save(self):
        self.d.save(self.current)

    def started(self, file):
        if file == self.queue[0].t.file:
            self.queue[0].ready = True
            self.p.enqueue(self.queue[0])
        else:
            for t in self.queue[1:]:
                if file == t.t.file:
                    t.ready = True

    def quit(self):
        self.d.quit()
        self.p.stop()
        del self.p

    def tick(self):
        self.emit(QtCore.SIGNAL("updatePosition(int, int)"), self.p.currentTime()/1000, self.current.duration)

    def shouldPlay(self):
        return (self.playing and not self.p.state() in (2,))
            
    def metaDataChanged(self):
        if self.shouldPlay():
            self.play()

    def stateChanged(self, n, o):
        if n == 5:
            self.log.warning(self.p.errorString())
            if "0x80004005" in self.p.errorString():
                self.log.error("Phonon critical error. Restarting Phonon...")
                self.quit()
                self.__init__()
                return
            self.skip()

        elif self.shouldPlay():
            self.play()

    def totalTimeChanged(self, d):
        self.current.duration = d//1000

    def currentSourceChanged(self, ns):
        if(not ns.url().isEmpty()):
            old = self.current
            if old:
                self.d.delete(old.file)
            self.current = self.queue[0].t
            self.emit(QtCore.SIGNAL("trackChanged(PyQt_PyObject, PyQt_PyObject)"), self.queue.pop(0).t, old)

    def prefinishMarkReached(self, a):
        if len(self.queue) < 2:
            self.getTracks()
        else:
            self.d.download(self.queue[0].t)

    def getTracks(self):
        if self.playing:
            self.emit(QtCore.SIGNAL("getTracks()"))

    def stop(self):
        self.playing = False
        if not self.p.currentSource().url().isEmpty():
            self.clear()
        self.emit(QtCore.SIGNAL("stop()"))

    def skip(self):
        q = self.queue
        self.clear()
        if q == []:
            self.getTracks()
        else:
            self.queue = q
            if not q[0].ready:
                self.d.download(q[0].t)
            else:
                self.p.enqueue(q[0])

    def clear(self):
        self.queue = []
        self.p.clear()

    def play(self):
        self.playing = True
        if not self.p.queue() and self.p.currentSource().url().isEmpty():
            self.getTracks()
        elif self.shouldPlay():
            self.p.stop()
            self.p.play()

    def feed(self, name, pl):
        if self.p.state() != 2 and pl == []:
            self.stop()
        self.emit(QtCore.SIGNAL("currentStation(QString)"), name)
        if len(self.queue) > 1:
            return
        for t in pl:
            t.file = NamedTemporaryFile().name
            self.queue.append(ExtendedMediaSource(t))
        if not self.queue:
            self.getTracks()
        elif not self.p.state() == 2:
            self.d.download(self.queue[0].t)
